﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;

namespace Patterns.Cache
{
	/// <summary>
	/// 	Defines a cached item.
	/// </summary>
	public class CachedItem
	{
		/// <summary>
		/// 	Gets or sets the value.
		/// </summary>
		/// <value>The value.</value>
		public object Value { get; set; }

		/// <summary>
		/// 	Gets or sets the start date.
		/// </summary>
		/// <value>The start date.</value>
		public DateTime StartDate { get; set; }

		/// <summary>
		/// 	Gets or sets the expiration date.
		/// </summary>
		/// <value>The expiration date.</value>
		public DateTime? ExpirationDate { get; set; }

		/// <summary>
		/// 	Gets or sets the sliding expiration.
		/// </summary>
		/// <value>The sliding expiration.</value>
		public TimeSpan? SlidingExpiration { get; set; }

		/// <summary>
		/// Determines whether the item has expired.
		/// </summary>
		/// <param name="adjustForUsage">if set to <c>true</c> adjust for usage.</param>
		/// <returns>
		/// 	<c>true</c> if the item has expired; otherwise, <c>false</c>.
		/// </returns>
		public bool HasExpired(bool adjustForUsage)
		{
			if (ExpirationDate.HasValue && DateTime.Now > ExpirationDate.Value) return true;
			if (SlidingExpiration.HasValue)
			{
				if ((DateTime.Now - StartDate) > SlidingExpiration.Value) return true;
				if (adjustForUsage) StartDate = DateTime.Now;
			}
			return false;
		}
	}
}